﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Speech.Synthesis;
using System.Threading;
using Newtonsoft.Json.Linq;
using LocalServer.Utils;
using WpfApp2;
using System.Windows.Controls.Primitives;
using Microsoft.Office.Interop.Excel;

namespace LocalServer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : System.Windows.Window
    {
        SynchronizationContext _syncContext = null;
        delegate void MyDelegate(Object value);
        SpeechSynthesizer speechSynthesizer = null;
        IntPtr icdev = IntPtr.Zero;
        private VzClientSDK.VZLPRC_GPIO_RECV_CALLBACK m_gpio_recvCB = null;
        static int handle = 0;
       public static int Leftcode;
        public static int Rightcode;


        public MainWindow()
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;
            speechSynthesizer = new SpeechSynthesizer();

            this.Loaded += Window_Loaded;
            this.Unloaded += Window_UnLoaded;

            CameraInitialize();
        }
        private void OnGPIORecv(int handle, int nGPIOId, int nVal, IntPtr pUserData)
        {
            int value = nVal;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            HttpServer server = App.GetHttpServer();
            if (null != server)
            {
                HttpServer.sendMsgEvent += Client_sendMsgEvent;
            }
            sendClientAutoWeigh();


            //string port1 = App.GetConfig().IDCardPort1;
            //string port2 = App.GetConfig().IDCardPort2;

            //String rate = App.GetConfig().IDCardPortBaudRate;
            //int handle = CommonInterface.OpenDevice(port1, rate, "");
            //if (handle <= 0)
            //{
            //    MessageBox.Show("打开设备1失败，错误代码：" + handle.ToString());
            //    return;
            //}

            //int handle1 = CommonInterface.OpenDevice(port2, rate, "");

            //if (handle1 <= 0)
            //{
            //    MessageBox.Show("打开设备2失败，错误代码：" + handle1.ToString());
            //    return;
            //}
            //icdev = Reader.hc_init(6, 115200);
            //if (icdev.ToInt32() > 0)
            //{
            //    StringBuilder ver = new StringBuilder(32);
            //    Reader.srd_ver(icdev, 0, ver);
            //    Reader.dv_beep(icdev, 30);
            //    MessageBox.Show(ver.ToString(0, 32));
            //}
            //else
            //{
            //}
        }


        private void Client_sendMsgEvent(Object obj)
        {
            MyDelegate d = new MyDelegate(DealClientMessage);
            this.Dispatcher.Invoke(d, obj);
        }

        public void CameraInitialize()//初始化摄像头
        {
            VzClientSDK.VzLPRClient_Setup();
            m_gpio_recvCB = new VzClientSDK.VZLPRC_GPIO_RECV_CALLBACK(OnGPIORecv);

            String[] RightArray = App.GetConfig().Camera_Right_VideoUrl.Split(',');
            String[] LeftArray = App.GetConfig().Camera_Left_VideoUrl.Split(',');
            short nPort;
            if (RightArray.Length == 4)
            {
                nPort = Int16.Parse(RightArray[1]);
                Rightcode = VzClientSDK.VzLPRClient_Open(RightArray[0], (ushort)nPort, RightArray[2], RightArray[3]);//打开设备}



            }
            if (LeftArray.Length==4)
            {
                nPort = Int16.Parse(LeftArray[1]);
                Leftcode = VzClientSDK.VzLPRClient_Open(LeftArray[0], (ushort)nPort, LeftArray[2], LeftArray[3]);//打开设备}
            }
            
        }

        private void Window_UnLoaded(object sender, RoutedEventArgs e)
        {
            int Handle = CommonInterface.GetCurrentDevice();

            int ret1 = CommonInterface.CloseDevice();
            if (ret1 != 0)
            {
                MessageBox.Show("关闭设备失败，错误代码：" + ret1.ToString());
                return;
            }

        }
        void DealClientMessage(Object obj)
        {
            
        }
        private void btn_StartServer_Click(object sender, RoutedEventArgs e)
        {
            byte[] byScreenName = System.Text.Encoding.UTF8.GetBytes(LedUtil.textScreenName);

            int nRet = ListenDll.LV_CreateScreen(byScreenName);
            //MessageBox.Show(nRet == 0 ? "创建屏幕成功\r\nCreate screen successfully" : "创建屏幕失败\r\nCreate screen failed");

            byScreenName = System.Text.Encoding.UTF8.GetBytes(LedUtil.textScreenName);
            byte[] byProgramId = System.Text.Encoding.UTF8.GetBytes(LedUtil.textProgramId);

            page pageInfo = new page();
            pageInfo.pageId = 0;
            pageInfo.resolution = "200X100";
            pageInfo.bgColor = "#000000";
            string strBgFileName = "";//本地的一个图片文件
            pageInfo.bgImg = strBgFileName;
            pageInfo.eqType = "Q5";
            pageInfo.pageTime = 20;
            pageInfo.guid = Guid.NewGuid().ToString();

            string strPageInfo = JsonExtension.ToJSON(pageInfo);
            byte[] byPageInfo = System.Text.Encoding.UTF8.GetBytes(strPageInfo);

            nRet = ListenDll.LV_AddPageToProgram(byScreenName, byProgramId, byPageInfo);
            //MessageBox.Show(nRet == 0 ? "添加页面成功\r\nAdd page successfully" : "添加页面失败\r\nAdd page failed");
            //                                               （id，left，top，width,height,text,size)  
            string strTextJson01 = LedUtil.createStaticTextArea(1, 2, 0, 170, 30, "", 0, 18);
            //string strTextJson01 = LedUtil.createStaticTextArea(1, 0, 0, 170, 60, "", 0,16);
            byte[] byTextInfo01 = System.Text.Encoding.UTF8.GetBytes(strTextJson01);
            //string strTextJson11 = LedUtil.createStaticTextArea(11, 124, 0, 170, 30, "", 0,18);
            //byte[] byTextInfo11 = System.Text.Encoding.UTF8.GetBytes(strTextJson11);
            //string strTextJson02 = LedUtil.createStaticTextArea(2, 0, 25, 170, 30, "", 0, 18);
            string strTextJson02 = LedUtil.createStaticTextArea(2, 0, 27, 170, 30, "", 0, 18);
            byte[] byTextInfo02 = System.Text.Encoding.UTF8.GetBytes(strTextJson02);
            //string strTextJson03 = LedUtil.createStaticTextArea(3, 0, 60, 170, 30, "", 0, 18);
            string strTextJson03 = LedUtil.createStaticTextArea(3, 0, 60, 170, 30, "", 0, 18);
            byte[] byTextInfo03 = System.Text.Encoding.UTF8.GetBytes(strTextJson03);

            //string strTextJson04 = LedUtil.createStaticTextArea(4, 0, 30, 170, 30, "", 1);
            //byte[] byTextInfo04 = System.Text.Encoding.UTF8.GetBytes(strTextJson04);

            byScreenName = System.Text.Encoding.UTF8.GetBytes(LedUtil.textScreenName);
            byProgramId = System.Text.Encoding.UTF8.GetBytes(LedUtil.textProgramId);

            nRet = ListenDll.LV_AddArea(byScreenName, byProgramId, 0, byTextInfo01);
            //nRet = ListenDll.LV_AddArea(byScreenName, byProgramId, 0, byTextInfo11);
            nRet = ListenDll.LV_AddArea(byScreenName, byProgramId, 0, byTextInfo02);
            nRet = ListenDll.LV_AddArea(byScreenName, byProgramId, 0, byTextInfo03);
            //nRet = ListenDll.LV_AddArea(byScreenName, byProgramId, 0, byTextInfo04);
          //  MessageBox.Show(nRet == 0 ? "添加静态区域成功\r\nAdd static area successfully" : "添加静态区域失败\r\nFailed to add static zone");

            byScreenName = System.Text.Encoding.UTF8.GetBytes(LedUtil.textScreenName);
            byte[] byIp = System.Text.Encoding.UTF8.GetBytes(App.GetConfig().LEDIP1);
            byProgramId = System.Text.Encoding.UTF8.GetBytes(LedUtil.textProgramId);
            byte[] byProgramName = System.Text.Encoding.UTF8.GetBytes(LedUtil.textProgramName);

            byte[] byPassword = System.Text.Encoding.UTF8.GetBytes("");

            nRet = ListenDll.LV_SendProgramToDevice(byScreenName, byIp, byProgramId, byProgramName, byPassword);
            //MessageBox.Show(nRet == 0 ? "发送节目成功\r\nSend the program successfully" : "发送节目失败\r\nSend the program Failed");

            List<ProgramPlan> listPlan = new List<ProgramPlan>();

            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);

            ProgramPlan plan1 = new ProgramPlan();
            plan1.createDate = Convert.ToInt64(ts.TotalMilliseconds);
            plan1.programId = LedUtil.textProgramId;
            plan1.programName = LedUtil.textProgramName;
            plan1.programType = 1;
            plan1.updateDate = Convert.ToInt64(ts.TotalMilliseconds);
            plan1.date = new List<ProgramPlan.Date>();
            plan1.planWeekDay = new List<int>();
            plan1.time = new List<ProgramPlan.Time>();
            plan1.isDefault = 1;

            listPlan.Add(plan1);


            string strPlanJson = JsonExtension.ToJSON(listPlan);//对象转为Json
            byte[] byPlanInfo = System.Text.Encoding.UTF8.GetBytes(strPlanJson);
            byIp = System.Text.Encoding.UTF8.GetBytes(App.GetConfig().LEDIP1);
            string strDefVideo = "";//如果是默认节目,同时默认节目中存在视频文件,该字符串才不为空字符串
            byte[] byDefVideo = System.Text.Encoding.UTF8.GetBytes(strDefVideo);

            nRet = ListenDll.LV_SendProgramPlan(byIp, byPlanInfo, byDefVideo);
            //MessageBox.Show(nRet == 0 ? "发送节目计划成功\r\nSuccessfully sent the program plan" : "发送节目计划失败\r\nFailed to send program plan");

            nRet = ListenDll.LV_CleanProgramTemporary();
           // MessageBox.Show(nRet == 0 ? "成功\r\nSuccess" : "失败\r\nFail");
        }
        private void btn_StartServer2_Click(object sender, RoutedEventArgs e)
        {
            byte[] byScreenName = System.Text.Encoding.UTF8.GetBytes(LedUtil.textScreenName);

            int nRet = ListenDll.LV_CreateScreen(byScreenName);
            //MessageBox.Show(nRet == 0 ? "创建屏幕成功\r\nCreate screen successfully" : "创建屏幕失败\r\nCreate screen failed");

            byScreenName = System.Text.Encoding.UTF8.GetBytes(LedUtil.textScreenName);
            byte[] byProgramId = System.Text.Encoding.UTF8.GetBytes(LedUtil.textProgramId);

            page pageInfo = new page();
            pageInfo.pageId = 0;
            pageInfo.resolution = "200X100";
            pageInfo.bgColor = "#000000";
            string strBgFileName = "";//本地的一个图片文件
            pageInfo.bgImg = strBgFileName;
            pageInfo.eqType = "Q5";
            pageInfo.pageTime = 20;
            pageInfo.guid = Guid.NewGuid().ToString();

            string strPageInfo = JsonExtension.ToJSON(pageInfo);
            byte[] byPageInfo = System.Text.Encoding.UTF8.GetBytes(strPageInfo);

            nRet = ListenDll.LV_AddPageToProgram(byScreenName, byProgramId, byPageInfo);
            //MessageBox.Show(nRet == 0 ? "添加页面成功\r\nAdd page successfully" : "添加页面失败\r\nAdd page failed");

            //string strTextJson01 = LedUtil.createStaticTextArea(1, 2, 0, 200, 30, "", 0, 18);
            //                                           （id，left，top，width,height,text,size)           
            string strTextJson01 = LedUtil.createStaticTextArea(1, 2, 0, 100, 30, "", 0, 18);
            byte[] byTextInfo01 = System.Text.Encoding.UTF8.GetBytes(strTextJson01);
            string strTextJson11 = LedUtil.createStaticTextArea(11, 124, 0, 170, 30, "", 0, 18);
            byte[] byTextInfo11 = System.Text.Encoding.UTF8.GetBytes(strTextJson11);
            //string strTextJson02 = LedUtil.createStaticTextArea(2, 0, 25, 170, 30, "", 0, 18)
            string strTextJson02 = LedUtil.createStaticTextArea(2, 0, 20, 200, 60, "", 0, 18);
            byte[] byTextInfo02 = System.Text.Encoding.UTF8.GetBytes(strTextJson02);
            //string strTextJson03 = LedUtil.createStaticTextArea(3, 0, 60, 170, 30, "", 0, 18);
            string strTextJson03 = LedUtil.createStaticTextArea(3, 0, 60, 170, 20, "", 0, 18);
            byte[] byTextInfo03 = System.Text.Encoding.UTF8.GetBytes(strTextJson03);

            string strTextJson04 = LedUtil.createStaticTextArea(4, 0, 30, 170, 30, "", 1);
            byte[] byTextInfo04 = System.Text.Encoding.UTF8.GetBytes(strTextJson04);

            byScreenName = System.Text.Encoding.UTF8.GetBytes(LedUtil.textScreenName);
            byProgramId = System.Text.Encoding.UTF8.GetBytes(LedUtil.textProgramId);

            nRet = ListenDll.LV_AddArea(byScreenName, byProgramId, 0, byTextInfo01);
            nRet = ListenDll.LV_AddArea(byScreenName, byProgramId, 0, byTextInfo11);
            nRet = ListenDll.LV_AddArea(byScreenName, byProgramId, 0, byTextInfo02);
            nRet = ListenDll.LV_AddArea(byScreenName, byProgramId, 0, byTextInfo03);
            nRet = ListenDll.LV_AddArea(byScreenName, byProgramId, 0, byTextInfo04);
            //MessageBox.Show(nRet == 0 ? "添加静态区域成功\r\nAdd static area successfully" : "添加静态区域失败\r\nFailed to add static zone");

            byScreenName = System.Text.Encoding.UTF8.GetBytes(LedUtil.textScreenName);
            byte[] byIp = System.Text.Encoding.UTF8.GetBytes(App.GetConfig().LEDIP2);
            byProgramId = System.Text.Encoding.UTF8.GetBytes(LedUtil.textProgramId);
            byte[] byProgramName = System.Text.Encoding.UTF8.GetBytes(LedUtil.textProgramName);

            byte[] byPassword = System.Text.Encoding.UTF8.GetBytes("");

            nRet = ListenDll.LV_SendProgramToDevice(byScreenName, byIp, byProgramId, byProgramName, byPassword);
            //MessageBox.Show(nRet == 0 ? "发送节目成功\r\nSend the program successfully" : "发送节目失败\r\nSend the program Failed");

            List<ProgramPlan> listPlan = new List<ProgramPlan>();

            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);

            ProgramPlan plan1 = new ProgramPlan();
            plan1.createDate = Convert.ToInt64(ts.TotalMilliseconds);
            plan1.programId = LedUtil.textProgramId;
            plan1.programName = LedUtil.textProgramName;
            plan1.programType = 1;
            plan1.updateDate = Convert.ToInt64(ts.TotalMilliseconds);
            plan1.date = new List<ProgramPlan.Date>();
            plan1.planWeekDay = new List<int>();
            plan1.time = new List<ProgramPlan.Time>();
            plan1.isDefault = 1;

            listPlan.Add(plan1);


            string strPlanJson = JsonExtension.ToJSON(listPlan);//对象转为Json
            byte[] byPlanInfo = System.Text.Encoding.UTF8.GetBytes(strPlanJson);
            byIp = System.Text.Encoding.UTF8.GetBytes(App.GetConfig().LEDIP2);
            string strDefVideo = "";//如果是默认节目,同时默认节目中存在视频文件,该字符串才不为空字符串
            byte[] byDefVideo = System.Text.Encoding.UTF8.GetBytes(strDefVideo);

            nRet = ListenDll.LV_SendProgramPlan(byIp, byPlanInfo, byDefVideo);
            //MessageBox.Show(nRet == 0 ? "发送节目计划成功\r\nSuccessfully sent the program plan" : "发送节目计划失败\r\nFailed to send program plan");

            nRet = ListenDll.LV_CleanProgramTemporary();
            //MessageBox.Show(nRet == 0 ? "成功\r\nSuccess" : "失败\r\nFail");
        }

        private void btn_StopServer_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            System.Windows.Application.Current.MainWindow.Hide();
        }

        private void btn_IDCard_Click(object sender, RoutedEventArgs e)
        {
            /*
            int ret = CommonInterface.SetTerminalLibrary("TerminalProtocolM03.dll");
            if (ret != 0)
            {
                MessageBox.Show("设置协议层动态库失败：" + ret);
            }*/
            String port = App.GetConfig().IDCardPort1;
            String rate = App.GetConfig().IDCardPortBaudRate;
            int handle = CommonInterface.OpenDevice(port, rate, "");
            if (handle <= 0)
            {
                MessageBox.Show("打开设备失败，错误代码：" + handle.ToString());
                return;
            }
            StringBuilder IdCardInfo = new StringBuilder(409600);
            int ret = CommonInterface.SdtReadCard(0, 1, IdCardInfo, 0);
            if (ret != 0)
            {
                MessageBox.Show("读取证件信息失败，错误代码：" + ret.ToString());
                return;
            }

            string[] CardInfo = IdCardInfo.ToString().Split(':');

            String name = CardInfo[1];
            String idNum = CardInfo[9];

            MessageBox.Show(idNum);

            int Handle = CommonInterface.GetCurrentDevice();

            ret = CommonInterface.CloseDevice();
            if (ret != 0)
            {
                MessageBox.Show("关闭设备失败，错误代码：" + ret.ToString());
                return;
            }
        }

        private void sendClientAutoWeigh()
        {

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "client");
            //jsonObj.Add("clientId", App.GetConfig().DeviceCode);
            jsonObj.Add("type", "UploadClientAutoWeigh");
            SendMessageUtils.SendNodeRedMsg("PostMessage/UploadClientAutoWeigh", jsonObj);
            string _autoWeigh = "true";
            jsonObj.Add("value", _autoWeigh);

            JObject reqObj = new JObject();
            reqObj.Add("type", "AutoWeigh");
            reqObj.Add("value", _autoWeigh);
            SendMessageUtils.SendNodeRedMsg("PostMessage/AutoWeighChange", reqObj);
            JObject reqObj1 = new JObject();
            SendMessageUtils.SendNodeRedMsg("PostMessage/GetWeight", reqObj1);
            JObject reqObj2 = new JObject();
            SendMessageUtils.SendNodeRedMsg("PostMessage/StartMonitor", reqObj2);
        }
    }
}
